param(
    [int]$Port = 8000
)

# Resolve script directory so this script can run from any working directory
$ScriptDir = $PSScriptRoot
Write-Host "Starting backend on port $Port from $ScriptDir ..."

# Prefer Python from local venv if available
$VenvPython = Join-Path $ScriptDir ".venv/Scripts/python.exe"
if (Test-Path $VenvPython) {
    $PythonExe = $VenvPython
} else {
    $PythonExe = "python"
}

# Try FastAPI (Uvicorn) first. --app-dir points to server folder so module "app.main:app" resolves correctly
& $PythonExe -m uvicorn app.main:app --reload --host 127.0.0.1 --port $Port --app-dir $ScriptDir

if ($LASTEXITCODE -ne 0) {
    Write-Warning "Uvicorn/FastAPI failed (exit $LASTEXITCODE). Falling back to simple_server.py"
    $SimpleServerPath = Join-Path $ScriptDir "simple_server.py"
    & $PythonExe $SimpleServerPath --host 127.0.0.1 --port $Port
}